using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Machine : MonoBehaviour
{
    public GameObject HurtNumber;
    public int health;
    private int HurtNum;
    private bool tillSleep=true;
    private Animator anim;
    private Collider2D coll;
    private Collider2D playerColl;
    public Collider2D coll1,coll2;
    public LayerMask playerLayer;
    public GameObject weapon;
    public GameObject door;
    public GameObject itemPrefab;
    private GameObject item;
    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        coll = GetComponent<Collider2D>();
        item = Instantiate(itemPrefab, transform.position, transform.rotation);
    }

    // Update is called once per frame
    void Update()
    {
        if (coll.IsTouchingLayers(playerLayer))
        {
            if (Input.GetKeyDown(KeyCode.E) && anim.GetCurrentAnimatorClipInfo(0)[0].clip.name == "Machine") 
            {
                Destroy(coll1.GetComponent<Machine>().item);
                Destroy(coll2.GetComponent<Machine>().item);
                coll1.GetComponent<Animator>().Play("Machine2");
                coll2.GetComponent<Animator>().Play("Machine2");
                coll.enabled = false;
                door.SetActive(true);
            }
        }
        if (health < 0 && anim.GetCurrentAnimatorClipInfo(0)[0].clip.name != "Machine") 
        {
            coll.enabled = false;
            anim.Play("Machine4");
            if (!coll1.isActiveAndEnabled && !coll2.isActiveAndEnabled) 
            {
                door.SetActive(false);
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            playerColl = collision;
        }
        if ((collision.gameObject.layer == LayerMask.NameToLayer("Bullet_Player") || collision.gameObject.layer == LayerMask.NameToLayer("Knife") )&& anim.GetCurrentAnimatorClipInfo(0)[0].clip.name != "Machine") 
        {
            if (collision.GetComponent<bullet>() != null)
            { HurtNum = collision.GetComponent<bullet>().damage; }
            if (collision.GetComponent<bullet2>() != null)
            { HurtNum = collision.GetComponent<bullet2>().damage; }
            Vector3 vector = new Vector2((float)UnityEngine.Random.Range(-20, 20) / 100, (float)UnityEngine.Random.Range(100, 140) / 100);
            GameObject gb = Instantiate(HurtNumber, transform.position + vector, transform.rotation);
            gb.GetComponent<TextMesh>().text = HurtNum.ToString();
            health -= HurtNum;
        }
    }
}
